<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Debug</title>
</head>
<body>
    <h1>WebSocket Connection Debug</h1>
    <button id="connectBtn">Connect to WebSocket</button>
    <div id="status">Not connected</div>
    <div id="messages"></div>

    <script>
        let socket = null;
        
        document.getElementById('connectBtn').addEventListener('click', () => {
            connectWebSocket();
        });
        
        function connectWebSocket() {
            const statusDiv = document.getElementById('status');
            const messagesDiv = document.getElementById('messages');
            
            statusDiv.textContent = 'Connecting...';
            
            // 连接到WebSocket服务器
            socket = new WebSocket('ws://localhost:3000');
            
            socket.onopen = () => {
                statusDiv.textContent = 'Connected';
                messagesDiv.innerHTML += '<p>Connected to WebSocket server</p>';
                
                // 发送测试消息
                const testMessage = {
                    type: 'user-join',
                    user: { 
                        id: 'debug_user_123', 
                        name: 'Debug User', 
                        color: '#FF0000',
                        documentId: 1
                    }
                };
                socket.send(JSON.stringify(testMessage));
                messagesDiv.innerHTML += '<p>Sent user-join message</p>';
            };
            
            socket.onmessage = (event) => {
                messagesDiv.innerHTML += `<p>Received: ${event.data}</p>`;
                console.log('Received message:', event.data);
                
                try {
                    const data = JSON.parse(event.data);
                    messagesDiv.innerHTML += `<p>Parsed message type: ${data.type || 'unknown'}</p>`;
                } catch (e) {
                    messagesDiv.innerHTML += `<p>Error parsing message: ${e.message}</p>`;
                }
            };
            
            socket.onclose = (event) => {
                statusDiv.textContent = 'Disconnected';
                messagesDiv.innerHTML += `<p>Disconnected: code=${event.code}, reason=${event.reason}</p>`;
            };
            
            socket.onerror = (error) => {
                statusDiv.textContent = 'Error';
                messagesDiv.innerHTML += `<p>Error: ${error.message}</p>`;
            };
        }
    </script>
</body>
</html>